<?php

class GroundController extends AppController {

    public $name = "Ground";
    public $uses = array(
        'Menu', 'GroundRequestQuality', 'UserRoleMenu', 'Service', 'Handler',
        'GroundRequest', 'GroundRequestScheduleService', 'GroundRequestSchedule',
        'GroundRequestScheduleAttachment', 'AirportFrequency'
    );
    public $helpers = array('DateFormat', 'Paginator');
    public $components = array('Upload', 'Pdf');
    public $paginate = array(
        'GroundRequest' => array(
            'contain' => array(
                'GroundRequestSchedule' => array(
                    'fields' => array('ref_no','status'),
                    'limit' => 1
                )
            ),
            'fields' => array('id', 'company_name'),
            'order' => array('id' => 'desc')
        ),
        'GroundRequestSchedule' => array(
            'contain' => array(
                'GroundRequest'
            ),
            //'fields' => array('ref_no','status'),
            'order' => array('GroundRequestSchedule.id' => 'desc'),
            'limit' => 30
        )
    );

    function beforeFilter() {

        if ($this->Session->check('user') == false) {
            $this->redirect('/admin/users/login/');
        }
    }

    public function admin_index() {
        $this->redirect(array('controller' => 'ground', 'action' => 'dashboard'));
    }

    /**
     * Action for Dashboard 
     */
    public function admin_dashboard() {
        $menus = $this->findMenu();

        $this->set(compact('menus'));
    }

    /**
     * Action for "Manage Requests"
     */
    public function admin_requests() {
        
    }
    
    /**
     * Action for Billing Interface 
     */
    public function admin_billing() {
        
    }
    
    /**
     * Action for Actual Billing Function
     */
    public function admin_bill() {
        
    }

    public function admin_request_template($schedule_id = NULL) {
        $this->set('schedule_ids', explode(",", $schedule_id));

        if (isset($_GET['print_form'])) {
            $this->layout = "print_layout";
        } else if (isset($_GET['download'])) {

            $this->GroundRequestSchedule->id = $schedule_id;
            $ref_no = $this->GroundRequestSchedule->field('ref_no');

            $this->Pdf->download("handling_request_{$ref_no}.pdf", '/elements/ground/handling_request_form', array(
                'schedule_ids' => $schedule_id
            ));
        }
    }

    public function admin_getreq($status) {

        $limit  = isset($_GET['limit'])  ? $_GET['limit']  : 30;
        $page   = isset($_GET['page'])   ? $_GET['page']   : 1;
        $offset = isset($_GET['offset']) ? $_GET['offset'] : ($page - 1) * $limit;


        $this->set('pg_offset', $offset + 1);
        $this->set('pg_size', $limit);

        if (isset($_POST['term']) && $_POST['term'] != "" && $_POST['filter'] != "") {
            $schedule_search_term = "";
            if ($_POST['filter'] == "cn") {
                $schedule_search_term = "GroundRequest.company_name";
            } elseif ($_POST['filter'] == "sn") {
                $schedule_search_term = "GroundRequestSchedule.ref_no";
            } elseif ($_POST['filter'] == "fn") {
                $schedule_search_term = "GroundRequestSchedule.arr_flight_num";
            } else if ($_POST['filter'] == "op") {
                $schedule_search_term = "GroundRequest.operator";
            } else if ($_POST['filter'] == "at") {
                $schedule_search_term = "GroundRequest.type";
            } else if ($_POST['filter'] == "rn") {
                $schedule_search_term = "GroundRequest.region";
            } else if ($_POST['filter'] == "lo") {
                $schedule_search_term = "GroundRequestSchedule.arr_dest";
            } else {
                $schedule_search_term = "GroundRequestSchedule.ref_no";
            }

            $groundRequests = $this->paginate('GroundRequestSchedule', array(
                $schedule_search_term . " LIKE" => "%" . $_POST['term'] . "%"
            ));

            $this->set('req', $groundRequests);
            $this->set('status', 'open');

            return;
        }

        $req = $this->paginate('GroundRequestSchedule', array('GroundRequestSchedule.status' => $status));
        $this->set(compact('req', 'status'));
    }
    
    public function admin_billing_list($status) {

        $limit  = isset($_GET['limit'])  ? $_GET['limit']  : 30;
        $page   = isset($_GET['page'])   ? $_GET['page']   : 1;
        $offset = isset($_GET['offset']) ? $_GET['offset'] : ($page - 1) * $limit;


        $this->set('pg_offset', $offset + 1);
        $this->set('pg_size', $limit);

        if (isset($_POST['term']) && $_POST['term'] != "" && $_POST['filter'] != "") {
            $schedule_search_term = "";
            if ($_POST['filter'] == "cn") {
                $schedule_search_term = "GroundRequest.company_name";
            } elseif ($_POST['filter'] == "sn") {
                $schedule_search_term = "GroundRequestSchedule.ref_no";
            } elseif ($_POST['filter'] == "fn") {
                $schedule_search_term = "GroundRequestSchedule.arr_flight_num";
            } else if ($_POST['filter'] == "op") {
                $schedule_search_term = "GroundRequest.operator";
            } else if ($_POST['filter'] == "at") {
                $schedule_search_term = "GroundRequest.type";
            } else if ($_POST['filter'] == "rn") {
                $schedule_search_term = "GroundRequest.region";
            } else {
                $schedule_search_term = "GroundRequestSchedule.ref_no";
            }

            $groundRequests = $this->paginate('GroundRequestSchedule', array(
                $schedule_search_term . " LIKE" => "%" . $_POST['term'] . "%"
            ));

            $this->set('req', $groundRequests);
            $this->set('status', 'open');

            return;
        }

        $req = $this->paginate('GroundRequestSchedule', array('GroundRequestSchedule.status' => $status));
        $this->set(compact('req', 'status'));
    }

    public function admin_del_service() {


        $id = $_POST['req_id'];
        $conditions = array(
            'GroundRequest.id' => $id
        );
        $gsdate = new GroundRequest();
        $gsdate->deleteAll($conditions, false);
        echo json_encode(array("status" => "del"));
        exit();
    }

    public function admin_del_req($req_id) {

        $this->autoRender = false;

        $schedules_open = $this->GroundRequestSchedule->find('count', array(
            'conditions' => array(
                'OR' => array(
                    'arr_ata' => NULL,
                    'dept_atd' => NULL
                ),
                'GroundRequestSchedule.ground_request_id' => $req_id
            )
                ));

        if ($schedules_open > 0) {
            echo json_encode(array('error' => 1, 'message' => 'ATD or ETD Not Entered For One Or More Flight Schedules'));
            return;
        }

        $this->GroundRequest->id = $req_id;
        $this->GroundRequest->save(array('jobsheet_status' => 'closed'));
        $this->GroundRequestSchedule->updateAll(array('status' => "'cancelled'"), array('ground_request_id' => $req_id));

        echo json_encode(array('error' => 0, "status" => "del"));
    }

    public function admin_schedule_edit($ground_request_id = NULL) {

        if (isset($_POST['data'])) {
            $this->autoRender = false;

            $user = $this->Session->read('user');

            if (isset($_POST['data']['GroundRequestSchedule']['id']) && $_POST['data']['GroundRequestSchedule']['id'] != "") {
                $_POST['data']['GroundRequestSchedule']['created_dt'] = date('Y-m-d H:i:s');
                $_POST['data']['GroundRequestSchedule']['created_by'] = $user['User']['id'];
            }

            // always indicate who modified this schedule
            $_POST['data']['GroundRequestSchedule']['modified_by'] = $user['User']['id'];

            $this->GroundRequestSchedule->create();
            $this->GroundRequestSchedule->save($_POST['data']);

            if (isset($_POST['data']['GroundRequestSchedule']['id']) && $_POST['data']['GroundRequestSchedule']['id'] == "") {
                $this->GroundRequestSchedule->save(array(
                    'GroundRequestSchedule' => array(
                        'ref_no' => 'SBG' . $this->GroundRequestSchedule->id . "-" . date('y')
                    )
                ));
            }

            echo json_encode(array('ground_request_schedule_id' => $this->GroundRequestSchedule->id));

            return;
        }

        if (isset($_GET['req_id'])) {
            $req_id = $_GET['req_id'];

            $grdates = $this->GroundRequestSchedule->find("first", array(
                'contain' => array(
                    'GroundRequestScheduleService' => array(
                        'fields' => array('id', 'name', 'contact_number'),
                        'Service' => array(
                            'fields' => array('name')
                        )
                    ),
                    'GroundRequestScheduleAttachment' => array(
                        'fields' => array('id', 'name', 'file_name', 'mime_type')
                    )
                ),
                'conditions' => array(
                    'GroundRequestSchedule.id' => $req_id
                ),
                'order' => array("GroundRequestSchedule.id" => "desc"))
            );

            $service_array = array();
            foreach ($grdates['GroundRequestScheduleService'] as $val) {
                $service_array[] = $val['service_id'];
            }

            $this->set(compact('services', 'service_array', 'grdates', 'req_id'));
        }

        $handlers = $this->Handler->findHandlers();

        $this->set('handlers', $handlers);
        $this->set('ground_request_id', $ground_request_id);
    }

    public function admin_schedule_delete($ground_request_schedule_id) {
        $this->autoRender = false;

        $this->GroundRequestSchedule->id = $ground_request_schedule_id;
        $this->GroundRequestSchedule->delete();
    }
    
    public function admin_schedule_cancel($ground_request_schedule_id) {
        $this->autoRender = false;

        $this->GroundRequestSchedule->id = $ground_request_schedule_id;
        $this->GroundRequestSchedule->save(array(
            'status' => 'cancelled'
        ));
    }
    
    public function admin_schedule_open($ground_request_schedule_id) {
        $this->autoRender = false;

        $this->GroundRequestSchedule->id = $ground_request_schedule_id;
        $this->GroundRequestSchedule->save(array(
            'status' => 'open'
        ));
    }

    public function admin_schedule_summary($ground_request_schedule_id) {

        $schedule = $this->GroundRequestSchedule->find("first", array(
            'contain' => array(
                'GroundRequestScheduleService' => array(
                    'Service' => array(
                        'fields' => array('name')
                    )
                ),
                'Handler' => array(
                    'fields' => array('name')
                ),
                'GroundRequest',
                'GroundRequestScheduleAttachment' => array(
                    'fields' => array('id', 'name', 'file_name', 'mime_type')
                )
            ),
            'conditions' => array(
                'GroundRequestSchedule.id' => $ground_request_schedule_id
                ))
        );

        $this->set('schedule', $schedule);
    }

    public function admin_schedule_actuals_update($schedule_id) {

        if (isset($_POST['data'])) {
            $this->autoRender = false;
            
            $completed = true;
            
            foreach($_POST['data']['GroundRequestSchedule'] as $key => $value) {
                if( $key != "id" && strtotime($value) == false ) {
                    $completed = false;
                    break;
                }
            }
            
            if( $completed ) {
                $_POST['data']['GroundRequestSchedule']['status'] = "completed";
            }
            
            else {
                $_POST['data']['GroundRequestSchedule']['status'] = "open";
            }
            
            $this->GroundRequestSchedule->save($_POST['data']['GroundRequestSchedule']);
            
            // post back
            echo json_encode($_POST['data']['GroundRequestSchedule']);
            
            return;
        }

        $schedule = $this->GroundRequestSchedule->find('first', array(
            'conditions' => array('GroundRequestSchedule.id' => $schedule_id),
            'recursive' => -1
                ));

        $this->set('schedule', $schedule);
    }

    public function admin_attachments_add($ground_request_schedule_id) {

        if (isset($_POST['data'])) {
            $this->autoRender = false;
            $user = $this->Session->read('user');

            if (isset($_FILES['attachments'])) {
                $attachments = $this->Upload->uploadFiles($_FILES['attachments']);
                $data = array();

                foreach ($attachments as $attachment) {
                    $filename = 'files/gra/' . $attachment['file_name'];
                    
                    if( !file_exists($filename) ) {
                        file_put_contents($filename, $attachment['data']);
                    }
                    
                    $data[] = array(
                        'name' => $_POST['data']['GroundRequestScheduleAttachment']['name'],
                        'ground_request_schedule_id' => $_POST['data']['GroundRequestScheduleAttachment']['ground_request_schedule_id'],
                        'mime_type' => $attachment['mime_type'],
                        'file_name' => $attachment['file_name'],
                        'attachment' => $filename,
                        'created_dt' => date('Y-m-d H:i:s'),
                        'created_by' => $user['User']['id']
                    );
                }

                $this->GroundRequestScheduleAttachment->saveAll($data);
            }
        }

        $this->set('ground_request_schedule_id', $ground_request_schedule_id);
    }

    public function admin_attachments_list($ground_request_schedule_id) {

        $attachments = $this->GroundRequestScheduleAttachment->find('all', array(
            'fields' => array('id', 'name', 'file_name', 'mime_type'),
            'conditions' => array('ground_request_schedule_id' => $ground_request_schedule_id),
            'order' => array('file_name'),
            'recursive' => -1
                ));

        $this->set('attachments', $attachments);
    }

    public function admin_attachments_view($ground_request_schedule_attachment_id) {
        $this->autoRender = false;

        $attachment = $this->GroundRequestScheduleAttachment->find('first', array(
            'conditions' => array('id' => $ground_request_schedule_attachment_id),
            'recursive' => -1
                ));

        header("Content-type: " . $attachment['GroundRequestScheduleAttachment']['mime_type']);
        header("Content-Disposition: inline; filename=\"" . $attachment['GroundRequestScheduleAttachment']['file_name'] . "\"");

        echo file_get_contents( $attachment['GroundRequestScheduleAttachment']['attachment'] );
    }

    public function admin_attachments_delete($ground_request_schedule_attachment_id) {
        $this->autoRender = false;
        $this->GroundRequestScheduleAttachment->id = $ground_request_schedule_attachment_id;
        $this->GroundRequestScheduleAttachment->delete();
    }

    public function admin_services() {

        $ground_request_id = $_GET['req_id'];

        $groundRequest = $this->GroundRequest->find('first', array(
            'conditions' => array('GroundRequest.id' => $ground_request_id),
            'recursive' => -1)
        );

        $schedules = $this->GroundRequestSchedule->find("all", array(
            'contain' => array(
                'GroundRequestScheduleService' => array(
                    'Service' => array(
                        'fields' => array('name')
                    )
                ),
                'Handler' => array(
                    'fields' => array('name')
                ),
                'GroundRequestScheduleAttachment' => array(
                    'fields' => array('id', 'name', 'file_name', 'mime_type')
                ),
                'GroundRequest' => array(
                    'fields' => array('jobsheet_status')
                )
            ),
            'conditions' => array(
                'GroundRequestSchedule.ground_request_id' => $ground_request_id
            )
        ));


        $this->set(compact('schedules', 'groundRequest', 'ground_request_id'));
    }

    public function admin_dashboard_list($type) {

        if ($type == "arrivals") {
            $conditions = array('GroundRequestSchedule.status' => 'open');
            $order = array('GroundRequestSchedule.id' => 'desc');
        }
        
        else if( $type == "departures" ) {
            $conditions = array('GroundRequestSchedule.status' => 'open');
            $order = array('GroundRequestSchedule.id' => 'desc');
        }
        
        else if( $type == "cancelled" ) {
            $conditions = array(
                'GroundRequestSchedule.status' => 'cancelled',
                'GroundRequest.jobsheet_status' => 'closed'
            );
            $order = array('GroundRequestSchedule.id' => 'desc');
        }
        
        else if( $type == "completed" ) {
            $conditions = array(
                'GroundRequestSchedule.status' => 'completed'
            );
            $order = array('GroundRequestSchedule.id' => 'desc');
        }

        $requests = $this->paginate('GroundRequestSchedule', $conditions);
        /*$requests = $this->GroundRequestSchedule->find('all', array(
            'contain' => array('GroundRequest'),
            'conditions' => $conditions,
            'order' => $order,
            'offset' => isset($_GET['offset']) ? $_GET['offset'] : 0,
            'limit' => 50)
        );*/
        
        $pages = $this->GroundRequestSchedule->find('count', array(
            'conditions' => $conditions
        ));

        $this->set('req', $requests);
        $this->set('type', $type);
        $this->set('pages', $pages);
        $this->set('limit', 50);
        $this->set('offset', isset($_GET['offset']) ? $_GET['offset'] : 0);
    }

    public function findMenu() {

        $user = $this->Session->read('user');

        $user_menus = $this->UserRoleMenu->find('list', array(
            'fields' => array("menu_id"),
            'conditions' => array('user_role_id' => $user['User']['user_role_id']),
            'recursive' => -1)
        );

        $menus = $this->Menu->find('all', array(
            'conditions' => array('id' => $user_menus, 'level' => 2, 'parent_id' => 2),
            'recursive' => -1,
            'order' => array('position'))
        );

        return $menus;
    }

    public function admin_portindex() {
        
    }

    public function admin_addairport() {
        $jobSheets = $this->JobSheet->findJobSheets();
        $this->set(compact('jobSheets'));
    }

    public function admin_editairport() {
        
    }

    public function admin_close($req_id) {

        $groundRequest['GroundRequest'] = array();
        $groundRequest['GroundRequest']['id'] = $req_id;
        $groundRequest['GroundRequest']['jobsheet_status'] = "closed";
        $this->GroundRequest->save($groundRequest);
        echo json_encode(array("status" => "true"));
        exit();
    }

    public function admin_crew_brief($schedule_id = null) {
        $this->set(compact('schedule_id'));
    }

    public function admin_crew_brief_print($schedule_id = null, $option = '') {
        $this->GroundRequestSchedule->id = $schedule_id;
        $ref_no = $this->GroundRequestSchedule->field('ref_no');
        
        if ($option == 'download') {
            $this->Pdf->download("crew_brief_{$ref_no}.pdf", '/elements/ground/crew_brief_summary', array('schedule_id' => $schedule_id));
            return;
        }

        $this->layout = "print_layout";
        $this->set(compact('schedule_id'));
        $this->set('title_for_layout', 'Crew Brief Document - ' . $ref_no );
    }

    public function admin_service_quality_report($req_shedule_id = null, $print_status = null) {

        if ($this->RequestHandler->isAjax() && isset($_POST['data']['GroundRequestQuality'])) {

            $this->autoRender = false;
            $this->GroundRequestQuality->save($_POST['data']['GroundRequestQuality']);

            return;
        } else {
            $req_data = $this->GroundRequestSchedule->find('first', array(
                'conditions' => array('GroundRequestSchedule.id' => $req_shedule_id))
            );

            $this->set(compact('req_shedule_id', 'req_data'));
        }
    }

    public function admin_service_quality_print($schedule_id, $option = null) {

        if ($option == 'download') {
            $this->GroundRequestSchedule->id = $schedule_id;
            $ref_no = $this->GroundRequestSchedule->field('ref_no');

            $this->Pdf->download("quality_request_{$ref_no}.pdf", '/elements/ground/quality_service_request', array('schedule_id' => $schedule_id));
            return;
        }

        $this->layout = "print_layout";
        $this->admin_service_quality_report($schedule_id, true);
    }

    public function admin_schedule_jobsheet_print($schedule_id, $option = '') {
        if ($option == 'download') {
            $this->GroundRequestSchedule->id = $schedule_id;
            $ref_no = $this->GroundRequestSchedule->field('ref_no');

            $this->Pdf->download("jobsheet_{$ref_no}.pdf", '/elements/ground/jobsheet_summary_handler', array('schedule_id' => $schedule_id));
            return;
        }

        //for finding all data associated with a  request
        $this->layout = "print_layout";
        $this->set(compact('schedule_id'));
    }

    public function admin_schedule_jobsheet($schedule_id) {
        $this->set(compact('schedule_id'));
    }

    public function admin_add_handRequest($id = null) {
        //this part means u are adding new data

        if ($this->RequestHandler->isAjax()) {

            if (!isset($_POST['data'])) {

                if ($id != null) {
                    $req_data = $this->GroundRequest->find('first', array(
                        'conditions' => array('id' => $id),
                        'recursive' => -1)
                    );

                    $this->set(compact('req_data', 'id'));
                    return;
                } else {
                    return;
                }
            } else {
                $this->autoRender = false;
                $this->GroundRequest->save($_POST['data']);

                $this->redirect("/admin/ground/schedule_edit/" . $this->GroundRequest->id);
            }

            echo json_encode(array("status" => true, "type" => "insert", "grid" => $grs->id));
        }
    }

    public function admin_listJobs() {
        if ($this->RequestHandler->isAjax()) {
            $type = isset($_GET['type']) ? $_GET['type'] : '';

            if ($type == "departures") {
                $this->set('jobsheets', $this->JobSheet->getDepartures());
            } else {
                $this->set('jobsheets', $this->JobSheet->getArrivals());
            }
        }
    }

    public function admin_send_handler($schedule_id = null) {
        if ($this->RequestHandler->isAjax() && isset($_POST['email_link'])) {


            $request_url = '/elements/ground/jobsheet_summary_handler';
            $quality_url = '/elements/ground/crew_brief_summary';

            $options = array();
            $options['schedule_id'] = $_POST['schedule_id'];
            if ((isset($_POST['handler_option']))) {

                $this->admin_pushemail($_POST['handler_email'], $request_url, $options);
            }

            if ((isset($_POST['job_quality_option']))) {

                $this->admin_pushemail($_POST['company_email'], $quality_url, $options);
            }
            echo json_encode(array("status" => true));
            exit();
        } else {

            //get the  handler email,then the  client email for hte crew brief
            $schedule = $this->GroundRequestSchedule->find("first", array(
                'fields' => array('id', 'handler_id', 'ground_request_id'),
                'contain' => array(
                    'GroundRequest' => array(
                        'fields' => array('company_email', 'company_name', 'company_contact')
                    ),
                    'Handler' => array(
                        'fields' => array('name', 'email')
                    ),
                    'GroundRequestScheduleAttachment' => array(
                        'fields' => array('id', 'name', 'file_name')
                    )
                ),
                'conditions' => array(
                    'GroundRequestSchedule.id' => $schedule_id
                    ))
            );

            $this->set(compact('schedule'));
        }
    }

    public function admin_pushemail($email_address, $message_url, $options) {

        $this->autoRender = false;
        App::import('Vendor', 'emailClass', array('file' => 'mailsupport/class.omime.php'));

        // Create omime object
        $email = omime::create('related');

        // Create text message
        $message = new omime('alternative');
        $this->set(compact('options'));

        /* Make sure the controller doesn't auto render. */
        $this->autoRender = false;
        /* Set up new view that won't enter the ClassRegistry */
        $view = new View($this, false);
        $this->set(compact('options'));
        $view->viewPath = 'elements';

        /* Grab output into variable without the view actually outputting! */
        $view_output = $view->render($message_url);
        $message->attachHTML($view_output);
        $email->addMultipart($message);
        // Send email

        $email->send($email_address, 'SBMANN-ADMINISTRATOR', 'from: SBMANN');
        //echo json_encode(array('code' => 0, 'msg' => 'Email Sent! Please Tap Here To Continue'));
    }

}

?>
